/*
 * ActualizarBodega.java
 *
 * Created on 25 de julio de 2007, 11:43 AM
 */

package administrador;
import java.sql.*;
import javax.swing.*;

/**
 *
 * @author  daniel1
 */
public class ActualizarBodega extends javax.swing.JFrame {
  String BDOrigen;
  String BDDestino;
  int opcionAct;
  //Conexiones:
  Conexion cOrigen;
  Conexion cDestino;
  
  //Si encero valores:
    boolean enceroVal=false;
    /** Creates new form ActualizarBodega */
    public ActualizarBodega(String bdOri,String bdDes,int opAct,boolean encero) {
        BDOrigen=bdOri;
        BDDestino=bdDes;
        opcionAct=opAct;
        initComponents();
        setVisible(true);
        setSize(623,700);
        realizoConexionesBD();
        cargoBodegas();
        enceroVal=encero;
    }
    
    public void realizoConexionesBD(){
    cOrigen=new Conexion(BDOrigen);
    cDestino=new Conexion(BDDestino);
    //Establesco las Conexiones:
    cOrigen.conectarBase();
    cDestino.conectarBase();
   
    }
    
    public void cargoBodegas(){
        //Cargos las bodegas del Origen
        ResultSet r1;
        r1=cOrigen.consultarBase("select * from bodega");
        
        ResultSet r2;
        r2=cDestino.consultarBase("select * from bodega");
        
        try {
            r1.beforeFirst();
            while(r1.next()){
                int codBodega=r1.getInt(1);
                String nomBodega=r1.getString(2);
                cb_origen.addItem(nomBodega);
                }  
            r2.beforeFirst(); 
            while(r2.next()){
                int codBodega=r2.getInt(1);
                String nomBodega=r2.getString(2);
                cb_destino.addItem(nomBodega);
                }
            
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
              
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        cb_origen = new javax.swing.JComboBox();
        cb_destino = new javax.swing.JComboBox();
        bt_iniciar = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        area = new javax.swing.JTextArea();
        jScrollPane2 = new javax.swing.JScrollPane();
        areaCant = new javax.swing.JTextArea();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Actualizando Bodegas"));
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel1.setText("Definiendo Bodegas");

        jLabel2.setText("Bodega Origen:");

        jLabel3.setText("Bodega Destino:");

        bt_iniciar.setText("Iniciar Proceso");
        bt_iniciar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_iniciarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel3)
                        .addComponent(jLabel2)))
                .addGap(26, 26, 26)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(cb_destino, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(cb_origen, 0, 199, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 69, Short.MAX_VALUE)
                .addComponent(bt_iniciar)
                .addGap(52, 52, 52))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cb_origen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(cb_destino, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(bt_iniciar, javax.swing.GroupLayout.DEFAULT_SIZE, 42, Short.MAX_VALUE)
                .addGap(19, 19, 19))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel4.setText("Resultados:");

        area.setColumns(20);
        area.setRows(5);
        jScrollPane1.setViewportView(area);

        areaCant.setColumns(20);
        areaCant.setRows(5);
        jScrollPane2.setViewportView(areaCant);

        jLabel5.setText("Igualando Inventarios");

        jLabel6.setText("Modificando Cantidades");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 375, Short.MAX_VALUE)
                .addComponent(jLabel5)
                .addGap(20, 20, 20))
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel6)
                .addContainerGap(459, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 573, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 573, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 310, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void bt_iniciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_iniciarActionPerformed
// TODO add your handling code here:
     /*   
   int opcionAct;
   Conexion cOrigen;
   Conexion cDestino; */
   
   igualoInventario();
   
   //Encero los valores de la bodega destino
   if(enceroVal==true){
   cDestino.actualizarBase("update producto set stock_total=0;");
   cDestino.actualizarBase("update itm_bodega set cantidad=0;");
   
   }
   
        if(opcionAct==0){
        areaCant.append("PROCESO DE SUMA");
        modificoBodega("cantidad+");
        }else if(opcionAct==1){
        areaCant.append("PROCESO DE RESTA");
         modificoBodega("cantidad-");
        //restaBodega();
        }else if(opcionAct==2){
        areaCant.append("PROCESO DE REEMPLAZO");
        modificoBodega("");
        //reemplazaBodega();
        }
        
    }//GEN-LAST:event_bt_iniciarActionPerformed
    
    public void modificoBodega(String simbolo){
    //Si el producto existe?
        //Actualizo
    //No existe?
        //Creo
    //Saco Bodegas:
    int bodegaO=cb_origen.getSelectedIndex()+1;
    int bodegaD=cb_destino.getSelectedIndex()+1;
    
    
    ResultSet rOrigen=cOrigen.consultarBase("select * from itm_bodega where cod_bodega="+bodegaO);
    areaCant.append("\nLa bodega origen tiene el codigo:"+bodegaO);
    //area.append(cOrigen.verResultados(rOrigen)+"\n");
    ResultSet rDestino=cDestino.consultarBase("select * from itm_bodega where cod_bodega="+bodegaD);
    areaCant.append("\nLa bodega destino tiene el codigo:"+bodegaD);    
    //area.append(cDestino.verResultados(rDestino)+"\n");
    
    areaCant.append("\n"+"Actualizo Productos de las Bodegas "+"\n");
    try{
        rOrigen.beforeFirst();
        while(rOrigen.next()){
                int codigoBod=rOrigen.getInt(1);    
                String codigoPro=rOrigen.getString(2);
                int cantidad=rOrigen.getInt(3);
                double cantMin=rOrigen.getDouble(4);
                
                //areaCant.append("\n Consulta::"+"select *  from itm_bodega  where cod_producto  like '"+codigoPro+"' and cod_bodega="+bodegaD);
                ResultSet rConsult=cDestino.consultarBase("select *  from itm_bodega  where cod_producto  like '"+codigoPro+"' and cod_bodega="+bodegaD);
                if(cDestino.obtenerFilas(rConsult)>0){
                //areaCant.append(" Si existe ");
               //Le Modifico la cantidad a la Existente:
                
                if(cDestino.actualizarBaseResp("update itm_bodega set cantidad="+simbolo+cantidad+" where cod_producto  like '"+codigoPro+"' and cod_bodega="+bodegaD)){
                //    areaCant.append("\nAcualiza: CodProducto:"+codigoPro+"\t"+"a cantidad="+simbolo+cantidad);    
                //    areaCant.append("Actualizacion Exitosa.");
                    }else{
                    areaCant.append("\nAcualiza: CodProducto:"+codigoPro+"\t"+"a cantidad="+simbolo+cantidad);
                    areaCant.append("=> Actualizacion Fallida.");
                    }
                    
                    
                 }else
                {
                areaCant.append("\n"+"No existe ");
                areaCant.append(" => Creo el Item del Producto en la Bodega:"+codigoPro+" con cant=0 ");
                
                cDestino.insertarDatos("Insert into itm_bodega values ("+bodegaD+",'"+codigoPro+"',0,"+cantMin+")");
                rOrigen.previous();
                 }
                    
            }
        }catch(SQLException sqle){
            System.out.println("Error al mostrar los resultados de la consulta");
            System.err.println(sqle);
        }
    
        
        
        
    
    }
    
    
    public void igualoInventario(){
    area.setText("");
    area.append("   PROCESO DE IGUALACION DE INVENTARIO  "+"\n"+"\n");
    area.append("IGUALANDO CATEGORIAS:  "+"\n");
    ResultSet rOrigen=cOrigen.consultarBase("select * from categoria");
    area.append(cOrigen.verResultados(rOrigen)+"\n");
    ResultSet rDestino=cDestino.consultarBase("select * from categoria");
    area.append(cDestino.verResultados(rDestino)+"\n");
    
    ResultSet rConsult;
    try{
        rOrigen.beforeFirst();
        while(rOrigen.next()){
                int codigo=rOrigen.getInt(1);
                String nombre=rOrigen.getString(2);
                rConsult=cDestino.consultarBase("select * from categoria where nombre like '"+nombre+"'");
                int filas=cDestino.obtenerFilas(rConsult);
                if(filas>0){
                    System.out.println("Si existeee:"+filas);
                    //cDestino.actualizarBase("update categoria set cod_categoria="+codigo+" where nombre like '"+nombre+"'");
                    area.append("\n"+"Si existe esta categoria: "+nombre);
                }else
                {
                    area.append("\n"+"No existe esta categoria: "+nombre);
                    area.append(" => Creo la categoria:");
                    rConsult=cDestino.consultarBase("select * from categoria");
                    int nuevafila=cDestino.obtenerFilas(rConsult)+1;
                    cDestino.insertarDatos("Insert into categoria values ("+nuevafila+",'"+nombre+"')");
                }
                    
            }
        }catch(SQLException sqle){
            System.out.println("Error al mostrar los resultados de la consulta");
            System.err.println(sqle);
        }
    
    
    area.append("\n"+"\n"+"IGUALANDO PRODUCTOS:  "+"\n");
    rOrigen=cOrigen.consultarBase("select * from producto");
    //area.append(cOrigen.verResultados(rOrigen)+"\n");
    rDestino=cDestino.consultarBase("select * from producto");
    //area.append(cDestino.verResultados(rDestino)+"\n");
    
  
    try{
        rOrigen.beforeFirst();
        while(rOrigen.next()){
                String codigo=rOrigen.getString(1);
                int codigoCat=rOrigen.getInt(2);
                String nombre=rOrigen.getString(3);
                String descripcion=rOrigen.getString(4);
                int stockTotal=rOrigen.getInt(5);
                double precioNormal=rOrigen.getDouble(6);
                int rank=rOrigen.getInt(7);
                double precioDistri=rOrigen.getDouble(10);
                
                rConsult=cDestino.consultarBase("select * from producto where cod_producto like '"+codigo+"'");
    
                if(cDestino.obtenerFilas(rConsult)>0){
                area.append("\n"+"Si existe esta Producto: "+codigo);
                area.append(" => Modifico al Producto:");
                cDestino.actualizarBase("update producto set cod_categoria="+codigoCat+", nombre='"+nombre+"', descripcion='"+descripcion+"', stock_total="+stockTotal+", precio_normal="+precioNormal+", ranking="+rank+", precio_distribucion="+precioDistri+"    where cod_producto like '"+codigo+"'");
//                cDestino.eliminarFila("delete from producto where cod_producto like '"+codigo+"'");
//                cDestino.insertarDatos("Insert into producto values ('"+codigo+"',"+codigoCat+",'"+nombre+"','"+descripcion+"',"+stockTotal+","+precioNormal+","+rank+")");
                }else
                {
                area.append("\n"+"No existe esta Producto: "+codigo);
                area.append(" => Creo la Producto:");
                String fecha=new java.sql.Date(System.currentTimeMillis()).toString();
                cDestino.insertarDatos("Insert into producto values ('"+codigo+"',"+codigoCat+",'"+nombre+"','"+descripcion+"',"+stockTotal+","+precioNormal+","+rank+",'"+fecha+"',"+precioDistri+")");
                }
                    
            }
        }catch(SQLException sqle){
            System.out.println("Error al mostrar los resultados de la consulta");
            System.err.println(sqle);
        }
    
    
    
    }
    
    /**
     * @param args the command line arguments
     */
   
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea area;
    private javax.swing.JTextArea areaCant;
    private javax.swing.JButton bt_iniciar;
    private javax.swing.JComboBox cb_destino;
    private javax.swing.JComboBox cb_origen;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration//GEN-END:variables
    
}
